<template>
  <div class="channel-list">
    <Breadcrumb>
      <BreadcrumbItem v-for="(name, i) in breadcrumb" :key="i">{{ name }}</BreadcrumbItem>
    </Breadcrumb>
    <div class="list-title">查询条件</div>
    <Row type="flex">
      <Form ref="formInline" :model="formInline" inline :label-width="0" label-position="left">
        <FormItem prop="status" label="">
          <Select v-model="formInline.status" placeholder="全部商户状态" style="minWidth:162px" filterable clearable>
            <Option v-for="item in MerchantStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="type" label="">
          <Select v-model="formInline.type" placeholder="全部商户类型" style="minWidth:162px" filterable clearable>
            <Option v-for="item in MerchantType" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="outsideSwitch" label="">
          <Select v-model="formInline.outsideSwitch" placeholder="全部业务联动" style="minWidth:162px" filterable clearable>
            <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="merchant2" label="">
          <Select v-model="formInline.merchant2" placeholder="是否M2商户" style="minWidth:162px" filterable clearable>
            <Option v-for="item in sfList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="provinceCode" label="">
          <Cascader ref="cascader" :data="pcList" v-model="depc" @on-change="selectPc" :load-data="loadData" placeholder="请选择省市区" style="width: 200px;"></Cascader>
        </FormItem>
        <FormItem prop="date" label="">
          <DatePicker ref="datePicker" type="daterange" @on-change="selectDate" placeholder="请选择日期" style="width: 200px;"></DatePicker>
        </FormItem>
        <FormItem label="" prop="searchContent">
          <Input type="text" v-model="formInline.searchContent" placeholder="商户名称、商户简称、uuid、域名、M2商户号" clearable style="width: 300px;" />
        </FormItem>
        <div class="form-but">
          <Button type="success" @click="getList">查询</Button>&nbsp;&nbsp;
          <Button @click="handleReset('formInline')">清空</Button>
        </div>
      </Form>
    </Row>
    <div>
      <Button type="primary" ghost @click="newChannel" class="add">新增</Button>
      <Table class="list-table" stripe border ref="selection" :columns="columns" :data="dataList" @on-select="selectOne" @on-select-all="selectAll" @on-select-cancel="cancelOne" @on-select-all-cancel="cancelAll"></Table>
      <div class="table-page">
        <div>
          <Button type="primary" ghost :disabled="!ids.length" @click="batchEnable()">批量启用商户</Button>&nbsp;&nbsp;
          <Button type="warning" ghost :disabled="!ids.length" @click="batchDisabled()">批量禁用商户</Button>&nbsp;&nbsp;
          <Button type="error" ghost :disabled="!ids.length" @click="batchDelete()">批量删除商户</Button>
        </div>
        <Page :total="total" show-sizer show-elevator show-total @on-change="changePageNum" @on-page-size-change="changePageSize" />
      </div>
    </div>
    <Modal width="768" @on-cancel="cancel" :mask-closable="false" footer-hide v-model="bindModalShow" title="绑定V10商户">
      <div class="report-content">
        <Form :ref="bindInfo.bindOtherCompany?'bindCompanyList':'bindList'" :model='bindInfo.bindOtherCompany?bindCompanyList:bindList' :label-width="140" label-position="left">
          <Row class="base-form">
            <FormItem label="商户名称：">
              {{ bindInfo.companyName }}
            </FormItem>
            <Row v-for="(item,index) in (bindInfo.bindOtherCompany?bindCompanyList.items:bindList.items)" :key="index">
              <h4 style="margin-bottom:10px">绑定关系{{index + 1}}:
                <Button @click="unbind(item.companyId)" v-if="bindInfo.bindOtherCompany&&!isDisabled" style="margin-left:20px">解除绑定</Button>
              </h4>
              <FormItem label="外部公司UUID：" :prop="'items.' + index + '.companyUuid'" :rules="{required: true, message: '此项不能为空', trigger: 'blur'}">
                <Input type="text" :disabled="isDisabled?false:bindInfo.bindOtherCompany?'disabled':false" v-model="item.companyUuid" placeholder="请输入"></Input>
              </FormItem>
              <FormItem label="渠道分销机构" :prop="'items.' + index + '.companyId'" :rules="{required: true, message: '此项不能为空', trigger: 'blur',type:'number'}">
                <Select v-model="item.companyId" placeholder="请选择" :disabled="isDisabled?false:bindInfo.bindOtherCompany?'disabled':false">
                  <Option v-for="val in distributionCompanyList" :value="val.value" :key="val.value" :label="val.label"></Option>
                </Select>
              </FormItem>
              <FormItem label="分销机构类型" :prop="'items.' + index + '.bindCompanyType'" :rules="{required: true, message: '此项不能为空', trigger: 'blur',type:'string'}">
                <Select v-model="item.bindCompanyType" placeholder="请选择" :disabled="isDisabled?false:bindInfo.bindOtherCompany?'disabled':false">
                  <Option v-for="val in bindCompanyTypeList" :value="val.value" :key="val.value" :label="val.value"></Option>
                </Select>
              </FormItem>
              <FormItem label="分销同步模式" :prop="'items.' + index + '.syncMode'" :rules="{required: true, message: '此项不能为空', trigger: 'blur',type:'string'}">
                <Select v-model="item.syncMode" placeholder="请选择" :disabled="isDisabled?false:bindInfo.bindOtherCompany?'disabled':false">
                  <Option v-for="val in syncModeList" :value="val.value" :key="val.value" :label="val.value"></Option>
                </Select>
              </FormItem>
            </Row>
            <Row style="text-align:center">
              <Button v-if="bindList.items.length<5&&bindCompanyList.items.length<5&&!bindInfo.bindOtherCompany" @click="addBind" :loading="isloading" type="success" ghost style="margin-right:10px">增加绑定关系</Button>
              <Button v-if="!bindInfo.bindOtherCompany" type="success" :loading="isloading" @click="bindSubmit('save')">保存绑定</Button>
              <Button v-if="bindInfo.bindOtherCompany&&!isDisabled" type="success" :loading="isloading" @click="editStatus">修改绑定</Button>
              <Row v-if="bindInfo.bindOtherCompany&&isDisabled">
                <Button :loading="isloading" @click="cancelEditStatus" style="margin-right:10px">取消</Button>
                <Button @click="addBind" :loading="isloading" type="success" ghost style="margin-right:10px">增加绑定关系</Button>
                <Button type="success" :loading="isloading" @click="bindSubmit('edit')">保存绑定</Button>
              </Row>
            </Row>
          </Row>
        </Form>
      </div>
    </Modal>
  </div>
</template>

<script>
import { formatTime } from "@/utils";
import Api from "@/api";

const commonApi = Api.Common;
const companyApi = Api.Company;

export default {
  name: "login",
  data() {
    return {
      breadcrumb: ["合作机构管理", "商户管理"],
      formInline: {
        status: "",
        type: "",
        outsideSwitch: "",
        merchant2: "",
        searchContent: "",
        createTimeEnd: "",
        createTimeStart: "",
        province: "",
        city: "",
        zone: "",
      },
      pcList: [],
      depc: [],
      MerchantStatus: [
        {
          label: "启用",
          value: "2",
        },
        {
          label: "禁用",
          value: "3",
        },
      ],
      MerchantType: [
        {
          label: "开发商",
          value: 20,
        },
        {
          label: "总代公司",
          value: 30,
        },
        {
          label: "试用商户",
          value: 40,
        },
      ],
      statusList: [
        {
          label: "不开通",
          value: "0",
        },
        {
          label: "开通",
          value: "1",
        },
      ],
      sfList: [
        {
          label: "是",
          value: "1",
        },
        {
          label: "否",
          value: "0",
        },
      ],
      bindCompanyTypeList: [
        {
          label: "SAAS10",
          value: "SAAS10",
        },
        {
          label: "SAAS20",
          value: "SAAS20",
        },
        {
          label: "SAASVIP",
          value: "SAASVIP",
        },
      ],
      syncModeList: [
        {
          label: "全量同步",
          value: "WHOLE",
        },
        {
          label: "标准同步",
          value: "NORMAL",
        },
        {
          label: "万豪定制",
          value: "WANHAO",
        },
        {
          label: "绑房定制",
          value: "BANGFANG",
        },
        {
          label: "懿皇定制",
          value: "YIHUANG",
        },
      ],
      dataList: [],
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "商户名称",
          key: "companyName",
          minWidth: 200,
          tooltip: true,
        },
        {
          title: "商户简称",
          key: "companyAbbreviation",
          minWidth: 120,
        },
        {
          title: "公司uuid",
          key: "id",
          minWidth: 100,
          render: (h, params) =>
            h(
              "a",
              {
                style: {
                  marginRight: "15px",
                },
                on: {
                  click: () => {
                    this.$store.commit("fixTag", {
                      label: "商户详情",
                      url: "channelProviderdetail?id=" + params.row.id,
                      path: "channelProviderdetail",
                    });
                    this.$router.push({
                      path: "/channelProviderdetail?id=" + params.row.id,
                    });
                  },
                },
              },
              "查看"
            ),
        },
        {
          title: "域名",
          key: "domain",
          minWidth: 180,
        },
        {
          title: "商户类型",
          key: "companyType",
          minWidth: 120,
        },
        {
          title: "位置",
          key: "address",
          minWidth: 200,
          tooltip: true,
        },
        {
          title: "联动业务",
          key: "outsideSwitch",
          minWidth: 120,
          render: (h, params) =>
            h("div", {}, params.row.outsideSwitch === "1" ? "开通" : "不开通"),
        },
        {
          title: "M2商户号",
          key: "merchantCode",
          minWidth: 200,
        },
        {
          title: "楼盘数",
          key: "numberOfProperties",
          minWidth: 100,
        },
        {
          title: "分销商数",
          key: "numberOfDistributors",
          minWidth: 100,
        },
        {
          title: "创建时间",
          key: "createTime",
          minWidth: 200,
          render: (h, params) =>
            h("div", {}, formatTime(params.row.createTime, "second")),
        },
        {
          title: "状态",
          key: "status",
          minWidth: 120,
          render: (h, params) =>
            h("div", {}, params.row.status === "3" ? "已禁用" : "启用"),
        },
        {
          title: "操作",
          key: "operate",
          minWidth: 350,
          fixed: "right",
          render: (h, params) =>
            h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  on: {
                    click: () => {
                      this.$store.commit("fixTag", {
                        label: "编辑商户",
                        url: "channelProviderupdate?id=" + params.row.id,
                        path: "channelProviderupdate",
                      });
                      this.$router.push({
                        path: "/channelProviderupdate?id=" + params.row.id,
                      });
                    },
                  },
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: params.row.status === "3" ? "success" : "warning",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title:
                          params.row.status === "3" ? "启用商户" : "禁用商户",
                        content:
                          "确定" + params.row.status === "3"
                            ? "启用商户?"
                            : "禁用商户?",
                        onOk: () => {
                          if (params.row.status === "3") {
                            this.enable(params.row.id);
                          } else {
                            this.prohibit(params.row.id);
                          }
                        },
                      });
                    },
                  },
                },
                params.row.status === "3" ? "启用" : "禁用"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px",
                    display:
                      params.row.status === "2" ? "none" : "inline-block",
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "删除商户",
                        content: "确定删除商户？",
                        onOk: () => {
                          this.deleteMerchant(params.row.id);
                        },
                      });
                    },
                  },
                },
                "删除"
              ),
              h(
                "Button",
                {
                  props: {
                    type: !params.row.bindOtherCompany ? "success" : "default",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  on: {
                    click: () => {
                      this.bindModal(params.row);
                    },
                  },
                },
                !params.row.bindOtherCompany ? "绑定V10商户" : "已绑V10商户"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "清理缓存",
                        content:
                          "将清除此公司下所有的用户、角色数据权限缓存,是否继续?",
                        onOk: () => {
                          this.cleanCompanyCache(params.row.id);
                        },
                      });
                    },
                  },
                },
                "清理缓存"
              ),
            ]),
        },
      ],
      total: 0,
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      ids: [],
      bindModalShow: false,
      bindInfo: {},
      bindList: {
        items: [
          {
            companyId: "",
            companyUuid: "",
            bindCompanyType: "",
            syncMode: "",
          },
        ],
      },
      isloading: false,
      distributionCompanyList: [],
      bindCompanyList: {
        items: [],
      },
      isDisabled: false,
    };
  },

  methods: {
    cancelAll(selection) {
      this.ids = [];
    },
    cancelOne(selection, row) {
      const i = this.ids.indexOf(row.id);
      this.ids.splice(i, 1);
    },
    selectAll(selection) {
      this.ids = [];
      this.ids = selection.map((item) => {
        return item.id;
      });
    },
    selectOne(selection, row) {
      this.ids.push(row.id);
    },
    // 获取已绑定商户列表
    async getBatchBindCompany() {
      const params = {
        id: this.bindInfo.id,
      };
      const { responseCode, data } = await this.$request(
        companyApi.findOtherCompany,
        params
      );
      if (responseCode === "1") {
        this.bindCompanyList.items = data;
        if (this.bindCompanyList.items.length === 0) {
          this.bindModalShow = false;
          this.getList();
        }
      }
    },
    // 获取分销机构列表
    async getListOptionDistributionCompany() {
      const params = {
        id: this.bindInfo.id,
      };
      const { responseCode, data } = await this.$request(
        companyApi.listOptionDistributionCompany,
        params
      );
      if (responseCode === "1") {
        this.distributionCompanyList = data;
      }
    },
    cancel() {
      const name = this.bindInfo.bindOtherCompany
        ? "bindCompanyList"
        : "bindList";
      this.$refs[name].resetFields();
    },
    // 展示弹窗（已绑/未绑）
    async bindModal(row) {
      const params = {
        id: row.id,
      };
      this.bindInfo = row;
      this.getListOptionDistributionCompany();

      if (row.bindOtherCompany) {
        this.getBatchBindCompany();
      } else {
        this.bindList.items = [
          {
            companyId: "",
            companyUuid: "",
          },
        ];
        this.isloading = false;
      }
      this.bindModalShow = true;
    },
    // 新增绑定关系
    addBind() {
      if (this.bindInfo.bindOtherCompany) {
        this.bindCompanyList.items.push({
          companyId: "",
          companyUuid: "",
          bindCompanyType: "",
          syncMode: "",
        });
      } else {
        this.bindList.items.push({
          companyId: "",
          companyUuid: "",
          bindCompanyType: "",
          syncMode: "",
        });
      }
    },
    // 保存绑定
    bindSubmit(type) {
      const name = this.bindInfo.bindOtherCompany
        ? "bindCompanyList"
        : "bindList";
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          this.isloading = true;
          const params = {
            id: this.bindInfo.id,
            companyList:
              type === "edit"
                ? this.bindCompanyList.items
                : this.bindList.items,
          };
          const { responseCode, responseMessage } = await this.$request(
            type === "edit"
              ? companyApi.batchUpdateBindCompany
              : companyApi.batchBindCompany,
            params
          );
          if (responseCode === "1") {
            this.$Message.success(type === "edit" ? "修改成功" : "绑定成功!");
            this.getList();
            this.isloading = false;
            this.bindModalShow = false;
            this.isDisabled = false;
            this.$refs[name].resetFields();
          } else {
            this.$Message.error(responseMessage);
            this.isloading = false;
            this.bindModalShow = false;
            this.isDisabled = false;
          }
        } else {
          this.$Message.error("请完善信息!");
        }
      });
    },
    // 修改绑定关系
    editStatus() {
      this.isDisabled = true;
    },
    // 取消修改
    cancelEditStatus() {
      this.getBatchBindCompany();
      this.isDisabled = false;
    },
    unbind(id) {
      this.$Modal.confirm({
        title: "解绑商户",
        content: "<p>是否确认解除绑定</p>",
        onOk: async () => {
          const { responseCode, responseMessage } = await this.$request(
            companyApi.deleteBindCompany,
            { id }
          );
          if (responseCode === "1") {
            this.$Message.success("解绑成功!");
            this.getBatchBindCompany();
          }
        },
        onCancel: () => {},
      });
    },
    newChannel() {
      this.$store.commit("fixTag", {
        label: "新增商户",
        url: "channelProvideradd",
      });
      this.$router.push({ path: "/channelProvideradd" });
    },
    // 批量启用
    async batchEnable() {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.batchEnableCompany, { ids: this.ids });
      if (responseCode === "1") {
        this.$Message.success("启用成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
        this.ids = [];
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("启用失败！");
      }
    },
    // 批量禁用
    async batchDisabled() {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.batchDisableCompany, {
        ids: this.ids,
      });
      if (responseCode === "1") {
        this.$Message.success("禁用成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
        this.ids = [];
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("禁用失败！");
      }
    },
    // 批量删除
    async batchDelete() {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.batchDeleteCompany, { ids: this.ids });
      if (responseCode === "1") {
        this.$Message.success("删除成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
        this.ids = [];
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("删除失败！");
      }
    },
    async prohibit(id) {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.disableCompany, { id });
      if (responseCode === "1") {
        this.$Message.success("禁用成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("禁用失败！");
      }
    },
    // 禁用缓存(用户及用户角色权限)
    async cleanCompanyCache(id) {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.cleanCompanyCache, { id });
      if (responseCode === "1") {
        this.$Message.success("清除成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("清除失败！");
      }
    },
    async enable(id) {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.enableCompany, { id });
      if (responseCode === "1") {
        this.$Message.success("启用成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("启用失败！");
      }
    },
    async deleteMerchant(id) {
      const {
        responseCode,
        responseMessage,
        responseType,
      } = await this.$request(companyApi.deleteCompany, { id });
      if (responseCode === "1") {
        this.$Message.success("删除成功！");
        this.page = { pageNum: 1, pageSize: 10 };
        this.getList();
      } else if (responseType === "ERROR") {
        this.$Message.error(responseMessage);
      } else {
        this.$Message.error("删除失败！");
      }
    },
    selectDate(date) {
      this.formInline.createTimeStart = date[0];
      this.formInline.createTimeEnd = date[1];
    },
    selectPc(value, selectedData) {
      this.formInline.province = value[0];
      this.formInline.city = value[1];
      this.formInline.zone = value[2];
    },
    async getProvince() {
      const { responseCode, data } = await this.$request(
        commonApi.listProvince
      );
      if (responseCode === "1") {
        data.forEach((item, index) => {
          item.loading = false;
          item.children = [];
        });
        this.pcList = data;
      }
    },
    loadData(item, callback) {
      const len = item.__label.split("/").length;
      item.loading = true;
      setTimeout(async () => {
        const { responseCode, data } = await this.$request(commonApi.listCity, {
          provinceId: item.value,
        });
        if (responseCode === "1") {
          if (len < 2) {
            data.forEach((city, index) => {
              city.loading = false;
              city.children = [];
            });
          }
          item.children = data;
        }
        item.loading = false;
        callback();
      }, 500);
    },
    // 分页变化
    changePageNum(pageNum) {
      this.getList({ pageNum });
    },
    // 条数变化
    changePageSize(pageSize) {
      this.getList({ pageSize });
    },
    async handleReset(name) {
      this.$refs[name].resetFields();
      this.$refs.datePicker.handleClear();
      this.$refs.cascader.clearSelect();
      this.formInline.createTimeStart = "";
      this.formInline.createTimeEnd = "";
      this.page = {
        pageNum: 1,
        pageSize: 10,
      };
      this.getList();
    },
    async getList(paramsPage = null) {
      let pageNum;
      let pageSize;
      let page;
      const statePage = this.page;
      if (paramsPage) {
        pageNum = paramsPage.pageNum || statePage.pageNum;
        pageSize = paramsPage.pageSize || statePage.pageSize;
        page = { pageNum, pageSize };
        this.page = { pageNum, pageSize };
      } else {
        page = statePage;
      }
      const formInline = this.formInline;
      const value = {};
      Object.keys(formInline).forEach((key) => {
        if (formInline[key]) {
          value[key] = formInline[key];
        }
      });
      const params = {
        page,
        ...value,
      };
      const { responseCode, data } = await this.$request(
        companyApi.listCompany,
        params
      );
      if (responseCode === "1") {
        data.list.forEach((item, index) => {
          const map = {
            1: "中介",
            20: "开发商",
            30: "总代公司",
            40: "试用商户",
          };
          item.companyType = map[item.companyType];
        });
        this.dataList = data.list;
        this.total = data.totalCount;
      }
    },
  },
  mounted() {
    this.getProvince();
    this.getList();
  },
};
</script>
<style lang="scss" scoped>
.channel-list {
  .ivu-form-item {
    margin-right: 20px;
  }
  .form-but {
    display: inline-block;
    margin-bottom: 24px;
  }
  .list-title {
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    color: #333;
  }
  .add {
    margin-bottom: 10px;
  }
  .table-page {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
  }
}
</style>
